'use strict';

// Declare app level module which depends on views, and components
angular.module('myApp', [
  'mgcrea.ngStrap'
]).
controller('liturgyEditor', ['$scope', '$http', '$aside', function($scope,$http,$aside){
  $scope.liturgicalCategories = [
    'Proper of Time',
    'Proper of Saints',
    'Commons',
    'Votive Masses'
  ];
  $scope.textTypes = [
    'Antiphon',
    'Prose',
    'Reading',
    'Psalm Tone',
    'Hymn',
    'Rubric'
  ];
  $scope.sectionTypes = {
    'Processional Chant': {
      name: ['Entrance Chant', 'Offertory Chant', 'Communion Chant'],
      sequential: false,
      list: [
        {
          sectionOption: 'Antiphon', //TODO: only section type with a default mode
          textType: 'Antiphon'
        }, {
          sectionOption: ''
        }
      ]
    },
    'Chant': {//ony type that can have verses (and default psalm tones) or mode.

    },
    'Reading': {  // hide mode and change psalm tone options to be "reading tone".
      name: ['First Reading', 'Second Reading', 'Gospel']  // freeform option
    },
    'Oration': {  //hide default mode

    },
    'Rubric': {  //only one child, with no musical settings

    },
    'Preface': {

    },
    'Title': { //no children

    },
    'Custom': {

    }
  };
  $http.get('../ac_psalmTone.php').success(function(data){
    $scope.psalmTones = data;
  }).error(function(){
    console.error('Error loading psalm tones');
    $scope.psalmTones = ['8g','8c','4e'];
  });
  $scope.languageNames = {
    la: 'Latin',
    en: 'English',
    es: 'Spanish'
  };
  $scope.liturgy = {
    sections: []
  };
  $scope.removeSubsection = function(section,list){
    if(angular.isArray(list)){
      list.splice(list.indexOf(section),1);
    } else {
      delete list[section];
    }
  }
  $scope.autoComplete = function(params) {
    return $http.get('../ac.php',{params:params}).then(function(response){
      return response.data;
    });
  };
  $scope.autoComplete({root:'liturgy'}).then(function(data){
    $scope.liturgyTitles = data;
  })
  var updateSavePath = function(){
    var liturgy = $scope.liturgy;
    if(!liturgy.title || !liturgy.category) {
      $scope.savePath = null;
      return;
    }
    var path = liturgy.title + (liturgy.qualifier? '/'+liturgy.qualifier : '') + '.json';
    switch(liturgy.category) {
      case 'Proper of Time':
        if(liturgy.season) path = liturgy.season + '/' + path;
        break;
      case 'Proper of Saints':
        if(liturgy.date) path = liturgy.date + '/' + path;
        break;
      default:
        if(liturgy.directory) path = liturgy.directory + '/' + path;
        break;
    }
    $scope.savePath = liturgy.category + '/' + path;
  };
  $scope.$watch('liturgy.title + "|" + liturgy.season + "|" + liturgy.date + "|" + liturgy.directory + "|" + liturgy.qualifier + "|" + liturgy.category', updateSavePath);
  $scope.load = function(loadPath) {
    $http.get('../library/liturgy-library/' + (loadPath || $scope.loadPath)).success(function(data){
      $scope.liturgy = data;
    });
  };
  $scope.save = function(savePath) {
    $http.post('../saveLiturgy.php',{path:savePath||$scope.savePath,data:angular.fromJson(angular.toJson($scope.liturgy))});
  };
  $scope.showLoad = function() {
    var loadAside = $aside({title:'Load', contentTemplate:'load-aside.html', placement: 'left', scope: $scope});
    $http.get('../dirTree.php?path=liturgy-library').success(function(data){
      loadAside.$scope.items = data;
    }).catch(function(error){
      loadAside.$scope.error = error;
    });
  };
}]).
filter('filterOut', function(){
  return function(list,filter){
    if(!angular.isArray(filter) && angular.isObject(filter)) filter = Object.keys(filter);
    if(filter.length==0) return list;
    if(angular.isArray(list)) {
      var result = [];
      for(var i=0; i<list.length; ++i) {
        if(filter.indexOf(list[i])<0) result.push(list[i]);
      }
    } else if(angular.isObject(list)) {
      var result = {};
      for(var i in list) {
        if(filter.indexOf(i)<0) result[i] = list[i];
      }
    } else return list;
    return result;
  }
}).
filter('hasKeys', function(){
  return function(object){
    return angular.isObject(object) && Object.keys(object).length;
  }
}).
filter('makeBold', function($sce){
  return function(text,filter){
    if(!filter) return $sce.trustAsHtml(text);
    return $sce.trustAsHtml(text.replace(new RegExp(filter,'gi'),'<b>$&</b>'));
  }
}).
directive('treeItem', ['$compile','$parse', function($compile,$parse) {
  var clickLink = function(item) {
    if(item.children) {
      this.open = !this.open;
    } else {
      this.$parent.rootTree.clickLink(item,this.dirPath);
    }
  }
  return {
    restrict: 'A',
    require: '^treeItems',
    scope: {
      item: '=treeItem'
    },
    template: "<div><span class='glyphicon' ng-class='item.children? (\"glyphicon-folder-\" + ((item.children.length&&open)? \"open\" : \"close\")):\"glyphicon-file\"'></span> <a href='' ng-click='clickLink(item)'><span ng-bind-html='item.name|makeBold:$parent.rootTree.filter'></span>{{item.children?'/':''}}</a></div>",
    controller: function($scope) {
      $scope.clickLink = clickLink;
      $scope.open = true;
    },
    link: function(scope, ele, attrs, treeController) {
      scope.dirPath = treeController.dirPath;
      $compile("<div ng-show='open' tree-items='item.children' dir-path='{{dirPath}}/{{item.name}}'></div>")(scope, function(cloned, scope){
        ele.append(cloned); 
      });
    }
  }
}]).
directive('treeItems', ['$timeout', function($timeout) {
  return {
    restrict: 'A',
    scope: {
      children: '=treeItems',
      filter: '=?treeFilter',
      dirPath: '@?',
      childOnClick: '&?'
    },
    template: "<div ng-repeat='child in children' tree-item='child' dir-path='{{dirPath}}'></div>",
    controller: function($scope, $element){
      $scope.clickLink = function(item, dirPath) {
        console.info($element)
        $scope.childOnClick({fullPath:(dirPath||'')+'/'+item.name,item:item,dirPath:dirPath});
      }
      this.dirPath = $scope.dirPath = $scope.dirPath || '';
      var parentTree = $element;
      $element.scope().treeScope = $scope;
      $scope.rootTree = $scope;
      while((parentTree = parentTree.parent().parent()) && parentTree.attr('tree-items')) {
        $scope.rootTree = parentTree.scope().treeScope;
        $scope.rootTreeElem = parentTree;
      }
    },
    link: function(scope, ele, attrs) {
    }
  }
}]);